package tyk.common;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.util.UUID;


/*
* 上传图片到阿里云Oss对象存储服务器上的工具类
* */
@Component
public class OssUtil {

    /*
    * 以下属性为密钥配置，验证身份的，错误的话，上传不了
    * */

    @Value("${aliyun.access-key-id}")
    private String accessKeyId;

    @Value("${aliyun.access-key-secret}")
    private String accessKeySecret;

    @Value("${aliyun.endpoint}")
    private String endpoint;

    @Value("${aliyun.bucketName}")
    String bucketName;

    /*
    * 该方法可以传递一张照片(file类型的),然后返回该照片的网络路径(照片路径)
    * */
    public String fileupload(MultipartFile file) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        String baseurl = "https://only-tyk.oss-cn-chengdu.aliyuncs.com/";
        String url = UUID.randomUUID().toString() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

        try {
            ossClient.putObject(bucketName, url, new ByteArrayInputStream(file.getBytes()));
        } catch (Exception oe) {
            throw new MyException("文件上传失败");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return baseurl + url;
    }
}
